<template>
	<view class="container">
		<!-- 顶部统计卡片 -->
		<view class="stats-card">
			<!-- 标题和统计信息 -->
			<view class="header-section">
				<text class="title">单个学生作业上传</text>
				<text class="subtitle">共{{studentList.length}}名学生 | 当前选择:
					{{selectedStudent ? selectedStudent.studentName : '无'}}</text>
			</view>

			<!-- 学科选择 -->
			<view class="subject-section">
				<view class="section-title">当前科目</view>
				<picker mode="selector" :range="subjects" :value="subjectIndex" @change="changeSubject">
					<view class="subject-picker">
						<text>{{currentSubject || '请选择学科'}}</text>
						<uni-icons type="arrowdown" size="18" color="#666"></uni-icons>
					</view>
				</picker>
			</view>

			<!-- 主题选择 -->
			<view class="theme-section">
				<view class="section-title">选择主题</view>
				<view class="theme-container">
					<scroll-view scroll-x class="theme-scroll" scroll-with-animation>
						<view class="theme-list">
							<view v-for="(theme, index) in themes" :key="index" class="theme-item"
								:class="{active: currentTheme === theme}" @click="selectTheme(theme)">
								{{theme}}
							</view>
						</view>
					</scroll-view>
					<view class="add-theme" @click="showAddThemeDialog">
						<uni-icons type="plus" size="20" color="#4a6cf7"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- 学生卡片列表 -->
		<view class="student-list">
			<view v-for="(student, index) in studentList" :key="student.userId" class="student-card"
				:class="{'selected': selectedStudent && selectedStudent.userId === student.userId}"
				@click="selectStudent(student)">
				<view class="card-content">
					<view class="avatar-wrapper">
						<image :src="student.aver || '/static/aver1.jpg'" class="avatar"></image>
						<view v-if="selectedStudent && selectedStudent.userId === student.userId" class="order-badge">
							✓
						</view>
					</view>
					<view class="student-info">
						<text class="text-bold">{{student.studentName}}</text>
						<text class="text-gray">{{student.grade}}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 已选照片展示区 -->
		<view v-if="selectedStudent" class="photo-gallery">
			<view class="gallery-header">
				<text class="gallery-title">{{selectedStudent.studentName}}的作业照片</text>
				<text class="gallery-count">({{selectedPhotos.length}}张)</text>
			</view>

			<scroll-view scroll-x class="photo-scroll">
				<view class="photo-list">
					<view v-for="(photo, index) in selectedPhotos" :key="index" class="photo-item">
						<image :src="photo.tempFilePath" class="photo-image" mode="aspectFill"
							@click="previewPhoto(index)"></image>
						<view class="upload-overlay" v-if="photo.uploadStatus === 'uploading'">
							<view class="progress-circle"
								:style="{transform: `rotate(${photo.uploadProgress * 3.6}deg)`}"></view>
							<!-- <text class="progress-text">{{photo.uploadProgress}}%</text> -->
						</view>
						<view class="status-icon" v-if="photo.uploadStatus === 'success'">
							<uni-icons type="checkmarkempty" size="24" color="#4CAF50"></uni-icons>
						</view>
						<view class="status-icon" v-if="photo.uploadStatus === 'error'">
							<uni-icons type="closeempty" size="24" color="#F44336"></uni-icons>
						</view>
						<view class="remove-photo" @click="removePhoto(index)">×</view>
					</view>
					<view class="add-photo-btn" @click="selectMorePhotos">
						<uni-icons type="plus" size="32" color="#4a6cf7"></uni-icons>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 底部操作区域 -->
		<view class="fixed-bottom">
			<button class="select-photos-btn" @click="selectPhotos" :disabled="!selectedStudent">
				添加照片
			</button>
			<button class="upload-btn" @click="handleUpload" :disabled="selectedPhotos.length === 0">
				上传作业 ({{selectedPhotos.length}}张)
			</button>
		</view>

		<!-- 添加主题对话框 -->
		<uni-popup ref="themeDialog" type="dialog">
			<uni-popup-dialog mode="input" title="添加新主题" placeholder="请输入主题名称"
				@confirm="addNewTheme"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import {
		globalVariable
	} from '../../configMy.js';

	export default {
		data() {
			return {
				grade: '',
				studentList: [],
				selectedStudent: null, // 当前选中的学生
				selectedPhotos: [], // 存储选择的照片
				teacher: {},
				subjects: [], // 学科列表
				currentSubject: '', // 当前选中学科
				subjectIndex: 0, // 当前选中学科索引
				themes: ['课堂作业', '课后练习', '单元测试', '假期作业'], // 默认主题列表
				currentTheme: '课堂作业', // 当前选中主题
				uploadProgress: 0, // 上传进度
				isUploading: false, // 是否正在上传
				uploadTasks: [] // 上传任务
			}
		},
		onLoad(option) {
			uni.getStorage({
				key: "teacher",
				success: (res) => {
					this.teacher = res.data;
					this.grade = option.grade;
					this.fetchSubjects();
				}
			});
		},
		methods: {
			async uploadAllPhotos() {
				this.isUploading = true;
				this.uploadTasks = [];

				// 显示全局上传提示
				uni.showLoading({
					title: `正在上传 (0/${this.selectedPhotos.length})`,
					mask: true
				});

				try {
					// 重置所有照片状态
					this.selectedPhotos = this.selectedPhotos.map(photo => ({
						...photo,
						uploadStatus: 'waiting',
						uploadProgress: 0
					}));

					// 创建上传任务数组
					const uploadPromises = this.selectedPhotos.map((photo, index) => {
						return new Promise((resolve, reject) => {
							const home = {
								studentId: this.selectedStudent.userId,
								studentName: this.selectedStudent.studentName,
								grade: this.selectedStudent.grade,
								hwType: this.currentSubject,
								hwEvent: this.currentTheme,
								teacherId: this.teacher.teacherId,
								teacherName: this.teacher.name
							};

							// 更新状态为上传中
							this.$set(this.selectedPhotos[index], 'uploadStatus', 'uploading');

							const task = uni.uploadFile({
								url: `${globalVariable}/uploadHomeWork`,
								filePath: photo.tempFilePath,
								name: 'file',
								formData: {
									homeWork: JSON.stringify(home)
								},
								success: (res) => {
									try {
										const data = JSON.parse(res.data);
										if (data.status === 1) {
											this.$set(this.selectedPhotos[index],
												'uploadStatus', 'success');
											resolve();
										} else {
											this.$set(this.selectedPhotos[index],
												'uploadStatus', 'error');
											reject(new Error(data.message || '上传失败'));
										}
									} catch (e) {
										this.$set(this.selectedPhotos[index],
											'uploadStatus', 'error');
										reject(e);
									}
								},
								fail: (err) => {
									this.$set(this.selectedPhotos[index], 'uploadStatus',
										'error');
									reject(err);
								}
							});

							// 监听上传进度
							task.onProgressUpdate = (res) => {
								this.$set(this.selectedPhotos[index], 'uploadProgress', res
									.progress);

								// 更新全局进度
								const completed = this.selectedPhotos.filter(p =>
									p.uploadStatus === 'success' || p.uploadStatus === 'error'
								).length;
								const total = this.selectedPhotos.length;

								uni.hideLoading();
								uni.showLoading({
									title: `正在上传 (${completed}/${total})`,
									mask: true
								});
							};

							this.uploadTasks.push(task);
						});
					});

					// 并行执行所有上传任务
					await Promise.all(uploadPromises);

					uni.hideLoading();
					uni.showToast({
						title: '上传完成',
						icon: 'success'
					});

					// 上传成功后清空已选照片
					this.selectedPhotos = [];
				} catch (error) {
					console.error('上传出错:', error);
					uni.hideLoading();
					uni.showToast({
						title: '上传失败: ' + (error.message || error),
						icon: 'none'
					});
				} finally {
					this.isUploading = false;
					this.uploadTasks = [];
				}
			},

			// 取消上传
			cancelUpload() {
				this.uploadTasks.forEach(task => {
					try {
						task.abort();
					} catch (e) {
						console.error('取消上传出错:', e);
					}
				});

				// 更新所有上传中的照片状态为已取消
				this.selectedPhotos = this.selectedPhotos.map(photo => {
					if (photo.uploadStatus === 'uploading') {
						return {
							...photo,
							uploadStatus: 'canceled',
							uploadProgress: 0
						};
					}
					return photo;
				});

				uni.hideLoading();
				uni.showToast({
					title: '已取消上传',
					icon: 'none'
				});

				this.isUploading = false;
				this.uploadTasks = [];
			},
			// 获取学科列表
			fetchSubjects() {
				uni.showLoading({
					title: '加载中...'
				});
				uni.request({
					url: `${globalVariable}/getTeacherSubject?grade=${this.grade}&teacherId=${this.teacher.teacherId}`,
					success: (res) => {
						uni.hideLoading();
						if (res.data.status === 1) {
							this.subjects = res.data.data.map(item => item.subject);
							if (this.subjects.length > 0) {
								this.currentSubject = this.subjects[0];
								this.fetchStudents();
							}
						} else {
							uni.showToast({
								title: res.data.message || '获取学科失败',
								icon: 'none'
							});
						}
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						});
					}
				});
			},

			// 获取学生列表
			fetchStudents() {
				uni.showLoading({
					title: '加载中...'
				});
				uni.request({
					url: `${globalVariable}/getStudentsByGrade?grade=${this.grade}`,
					success: (res) => {
						uni.hideLoading();
						if (res.data.status == 1) {
							this.studentList = res.data.data.map(item => {
								return {
									...item,
									aver: item.avatar || '/static/aver1.jpg'
								}
							});
						} else {
							uni.showToast({
								title: '加载失败',
								icon: 'none'
							});
						}
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						});
					}
				});
			},

			// 切换学科
			changeSubject(e) {
				this.subjectIndex = e.detail.value;
				this.currentSubject = this.subjects[this.subjectIndex];
				this.selectedStudent = null;
				this.selectedPhotos = [];
				this.fetchStudents();
			},

			// 选择主题
			selectTheme(theme) {
				this.currentTheme = theme;
			},

			// 显示添加主题对话框
			showAddThemeDialog() {
				this.$refs.themeDialog.open();
			},

			// 添加新主题
			addNewTheme(themeName) {
				if (themeName && !this.themes.includes(themeName)) {
					this.themes.unshift(themeName);
					this.currentTheme = themeName;
				}
				this.$refs.themeDialog.close();
			},

			// 选择学生
			selectStudent(student) {
				if (this.selectedStudent && this.selectedStudent.userId === student.userId) {
					this.selectedStudent = null;
					this.selectedPhotos = [];
				} else {
					this.selectedStudent = student;
					// 可以在这里加载该学生已有的本地照片
				}
			},

			// 选择照片
			selectPhotos() {
				if (!this.selectedStudent) {
					uni.showToast({
						title: '请先选择学生',
						icon: 'none'
					});
					return;
				}

				uni.chooseImage({
					count: 9, // 最多9张
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						// 添加新照片到已选列表
						const newPhotos = res.tempFiles.map(file => ({
							tempFilePath: file.path,
							studentId: this.selectedStudent.userId,
							uploadStatus: 'waiting'
						}));

						this.selectedPhotos = [...this.selectedPhotos, ...newPhotos];
					}
				});
			},

			// 选择更多照片
			selectMorePhotos() {
				const remaining = 9 - this.selectedPhotos.length;
				if (remaining <= 0) {
					uni.showToast({
						title: '最多只能上传9张照片',
						icon: 'none'
					});
					return;
				}

				this.selectPhotos();
			},

			// 预览照片
			previewPhoto(index) {
				const urls = this.selectedPhotos.map(photo => photo.tempFilePath);
				uni.previewImage({
					urls: urls,
					current: index
				});
			},

			// 移除照片
			removePhoto(index) {
				this.selectedPhotos.splice(index, 1);
			},

			// 处理上传
			async handleUpload() {
				if (this.selectedPhotos.length === 0) {
					uni.showToast({
						title: '请先选择照片',
						icon: 'none'
					});
					return;
				}

				if (this.isUploading) {
					uni.showToast({
						title: '正在上传中...',
						icon: 'none'
					});
					return;
				}

				uni.showModal({
					title: '确认上传',
					content: `确定要上传${this.selectedPhotos.length}张照片给${this.selectedStudent.studentName}吗？`,
					success: async (res) => {
						if (res.confirm) {
							this.isUploading = true;
							this.uploadProgress = 0;

							try {
								await this.uploadAllPhotos();
								uni.showToast({
									title: '上传成功',
									icon: 'success'
								});
								this.selectedPhotos = [];
							} catch (error) {
								console.error('上传出错:', error);
								uni.showToast({
									title: '上传失败: ' + (error.message || error),
									icon: 'none'
								});
							} finally {
								this.isUploading = false;
							}
						}
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* 添加照片上传状态样式 */
	.photo-item {
		position: relative;
		/* ...其他样式不变... */

		.upload-overlay {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background: rgba(0, 0, 0, 0.5);
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;

			.progress-circle {
				width: 50rpx;
				height: 50rpx;
				border-radius: 50%;
				border: 4rpx solid rgba(255, 255, 255, 0.2);
				border-top-color: #4a6cf7;
				animation: spin 1s linear infinite;
				margin-bottom: 10rpx;
			}

			.progress-text {
				color: white;
				font-size: 24rpx;
				font-weight: bold;
			}
		}

		.status-icon {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			background: rgba(255, 255, 255, 0.8);
			width: 50rpx;
			height: 50rpx;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}

	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}

	.container {
		padding: 30rpx;
		min-height: 100vh;
		background-image:
			radial-gradient(circle at 10% 20%, rgba(255, 79, 10, 0.1) 0%, transparent 20%),
			radial-gradient(circle at 90% 80%, rgba(38, 10, 255, 0.1) 0%, transparent 20%);
	}

	.stats-card {
		background: rgba(255, 255, 255, 0.9);
		backdrop-filter: blur(20px);
		border-radius: 24rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
		border: 1px solid rgba(255, 255, 255, 0.4);
	}

	.header-section {
		margin-bottom: 30rpx;

		.title {
			display: block;
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 10rpx;
		}

		.subtitle {
			display: block;
			font-size: 24rpx;
			color: #888;
		}
	}

	.subject-section {
		margin-bottom: 30rpx;

		.section-title {
			font-size: 26rpx;
			color: #666;
			margin-bottom: 16rpx;
		}

		.subject-picker {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx 30rpx;
			background: rgba(255, 255, 255, 0.8);
			border-radius: 50rpx;
			border: 1px solid rgba(0, 0, 0, 0.1);
			font-size: 28rpx;
			color: #333;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		}
	}

	.theme-section {
		.section-title {
			font-size: 26rpx;
			color: #666;
			margin-bottom: 16rpx;
		}

		.theme-container {
			display: flex;
			align-items: center;
		}

		.theme-scroll {
			width: 80%;
			flex: 1;
			white-space: nowrap;
			height: 80rpx;
		}

		.theme-list {
			display: inline-flex;
			height: 100%;
		}

		.theme-item {
			display: inline-flex;
			align-items: center;
			padding: 0 30rpx;
			margin-right: 20rpx;
			height: 70rpx;
			background: rgba(255, 255, 255, 0.6);
			border-radius: 40rpx;
			font-size: 26rpx;
			color: #666;
			border: 1px solid rgba(0, 0, 0, 0.1);
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

			&.active {
				background: #4a6cf7;
				color: white;
				font-weight: bold;
			}
		}

		.add-theme {
			width: 70rpx;
			height: 70rpx;
			margin-left: 20rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			background: rgba(255, 255, 255, 0.6);
			border-radius: 50%;
			border: 1px dashed #4a6cf7;
		}
	}

	.student-list {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 20rpx;
		margin-bottom: 160rpx;
	}

	.student-card {
		background: rgba(255, 255, 255, 0.25);
		backdrop-filter: blur(10px);
		border-radius: 20rpx;
		padding: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		transition: all 0.3s ease;
		position: relative;

		&.selected {
			background: rgba(100, 149, 237, 0.3);
			transform: scale(0.98);
			border: 2rpx solid #4a6cf7;
		}

		.card-content {
			display: flex;
			flex-direction: column;
			align-items: center;
		}

		.avatar-wrapper {
			position: relative;
			width: 120rpx;
			height: 120rpx;
			margin-bottom: 10rpx;

			.avatar {
				width: 100%;
				height: 100%;
				border-radius: 50%;
				object-fit: cover;
				border: 2rpx solid rgba(255, 255, 255, 0.5);
			}

			.order-badge {
				position: absolute;
				top: -10rpx;
				right: -10rpx;
				width: 40rpx;
				height: 40rpx;
				background: #4a6cf7;
				color: white;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 24rpx;
				font-weight: bold;
			}
		}

		.student-info {
			display: flex;
			flex-direction: column;
			align-items: center;
			text-align: center;

			.text-bold {
				margin-bottom: 5rpx;
				font-weight: bold;
				font-size: 28rpx;
			}

			.text-gray {
				color: #888;
				font-size: 24rpx;
			}
		}
	}

	.photo-gallery {
		position: fixed;
		bottom: 160rpx;
		left: 30rpx;
		right: 30rpx;
		background: rgba(255, 255, 255, 0.9);
		border-radius: 24rpx;
		padding: 20rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
		z-index: 10;

		.gallery-header {
			display: flex;
			align-items: center;
			margin-bottom: 20rpx;

			.gallery-title {
				font-size: 28rpx;
				font-weight: bold;
				color: #333;
			}

			.gallery-count {
				font-size: 24rpx;
				color: #4a6cf7;
				margin-left: 10rpx;
			}
		}

		.photo-scroll {
			width: 100%;
			white-space: nowrap;
			height: 150rpx;
		}

		.photo-list {
			display: inline-flex;
			height: 100%;
		}

		.photo-item {
			position: relative;
			width: 140rpx;
			height: 140rpx;
			margin-right: 20rpx;
			border-radius: 12rpx;
			overflow: hidden;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

			.photo-image {
				width: 100%;
				height: 100%;
			}

			.remove-photo {
				position: absolute;
				top: 0;
				right: 0;
				width: 40rpx;
				height: 40rpx;
				background: rgba(255, 0, 0, 0.7);
				color: white;
				border-radius: 0 0 0 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 32rpx;
				font-weight: bold;
			}
		}

		.add-photo-btn {
			width: 140rpx;
			height: 140rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			background: rgba(255, 255, 255, 0.6);
			border: 2rpx dashed #4a6cf7;
			border-radius: 12rpx;
		}
	}

	.fixed-bottom {
		position: fixed;
		bottom: 30rpx;
		left: 30rpx;
		right: 30rpx;
		display: flex;
		justify-content: space-between;

		button {
			flex: 1;
			margin: 0 10rpx;
			border-radius: 50rpx;
			font-size: 28rpx;
			transition: all 0.3s ease;

			&[disabled] {
				background: #cccccc !important;
				box-shadow: none !important;
				color: #999999 !important;
				opacity: 0.7;
			}
		}

		.select-photos-btn {
			background: linear-gradient(135deg, #6e8efb 0%, #4a6cf7 100%);
			color: white;
			box-shadow: 0 8rpx 20rpx rgba(74, 108, 247, 0.3);
		}

		.upload-btn {
			background: linear-gradient(135deg, #4CAF50 0%, #2E7D32 100%);
			color: white;
			box-shadow: 0 8rpx 20rpx rgba(46, 125, 50, 0.3);
		}
	}
</style>